package com.usian.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.search.UserSearchDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.search.client.ApBehaviorEntryClient;
import com.usian.search.service.ApUserSearchService;
import com.usian.search.service.SearchService;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * ClassName: SearchServiceImpl
 * Author:   WGG
 * Date:    2022-12-2022/12/10-11:17
 * Version: 1.0
 * Description:
 */
@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ApBehaviorEntryClient apBehaviorEntryClient;

    @Autowired
    private ApUserSearchService apUserSearchService;

    @Override
    public ResponseResult findByTitle(UserSearchDto dto){
        //校验参数
        if (dto.getSearchWords()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //获取当前登录用户id
        ApUser user = AppThreadLocalUtils.getUser();
        //判断当前用户是否登录
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryClient.showBehavior(user.getId(), dto.getEquipmentId());
        if (apBehaviorEntry.getType()==0){
            apUserSearchService.saveApUserSearch(dto.getEquipmentId(),dto.getSearchWords());
        }else {
            apUserSearchService.saveApUserSearch(user.getId(),dto.getSearchWords());
        }

        ArrayList<HashMap<String, Object>> arrayList = null;
        try {
            //创建request对象
            SearchRequest request = new SearchRequest("app_info_article");
            //创建queryBuild条件查询器
            request.source().query(QueryBuilders.multiMatchQuery(dto.getSearchWords(),"title","content"));
            //排序
            request.source().sort("publishTime", SortOrder.DESC);
            //分页
            request.source().from((dto.getPageNum()-1)*dto.getPageSize()).size(dto.getPageSize());
            //调用查询的方法
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            //解析response对象
            arrayList = responseHandle(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseResult.okResult(arrayList);

    }
    //解析方法
    public ArrayList<HashMap<String, Object>> responseHandle(SearchResponse response){
        ArrayList<HashMap<String, Object>> arrayList = new ArrayList<>();
        HashMap<String,Object> map = new HashMap();
        //获取hits
        SearchHits hits = response.getHits();
        //获取总的记录数
        long total = hits.getTotalHits().value;
        map.put("total", total);
        arrayList.add(map);
        //获取具体的数据
        SearchHit[] hitsHits = hits.getHits();
        //遍历数组
        for (SearchHit hit : hitsHits) {
            String sourceAsString = hit.getSourceAsString();
            //解析json数据
            HashMap hashMap = JSON.parseObject(sourceAsString, HashMap.class);
            arrayList.add(hashMap);
        }
        return arrayList;
    }


}
